import React, { useEffect, useState } from 'react'
import styles from './search.module.scss'
import Image from 'next/image'
import {storage} from '@/utils/utils'
import Router from 'next/router'
import searchTermModel from 'pages/model/search-term'
import {Tooltip, Input, Modal, Divider, List, Button} from 'antd'
import {SearchOutlined, DeleteOutlined, CloseOutlined} from '@ant-design/icons'
import Ctrl from '@/public/images/ctrl.svg'
const {Search} = Input

function SearchBar (props) {
  // eslint-disable-next-line react/prop-types
  const { searchWord }  = props
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [searchTermList, setSearchTermList] = useState([])
  const [searchTermDefault, setSearchTermDefault] = useState(null)
  useEffect(() => {
    document.onkeydown = e => {       
      if (e.ctrlKey  && e.key === 'q') {
        setIsModalVisible(true)
      }
    }
  }, [])
  //  关闭modal
  const close = () => {
    setIsModalVisible(false)
  }
  const searchBox = () => {
    setIsModalVisible(true)
  }
  const onSearch = value => {
    if (!value) value = searchTermDefault
    const historyList = storage.get('next_blog_search_history')
    searchTermModel.updateUserSearchWord({
      data: {
        id: JSON.parse(storage.get('next_blog_userInfo'))?.id,
        name: value
      }
    }).then(data => {
      console.log(data)
    })
    if (historyList && historyList.length) {
      let isHas = true
      historyList.forEach(item => {
        if (item.id === JSON.parse(storage.get('next_blog_userInfo'))?.id) {
          !item.historyList.includes(value) && item.historyList.push(value)
          isHas = false
        }
      })
      isHas && historyList.push({id: JSON.parse(storage.get('next_blog_userInfo'))?.id, historyList: [value]})
      storage.set('next_blog_search_history', historyList)
    } else {
      storage.set('next_blog_search_history', [{id: JSON.parse(storage.get('next_blog_userInfo'))?.id, historyList: [value]}])
    }
    setIsModalVisible(false)
    Router.push({pathname: '/search-result', query: {word: value}})
  }
  const [searchHistory, setSearchHistory] = useState([])
  const [deleteStatus, setDeleteStatus] = useState(false)
  useEffect(() => {
    const historyList = storage.get('next_blog_search_history')
    if (historyList && historyList.length) {
      historyList.forEach(item => {
        if (item.id === JSON.parse(storage.get('next_blog_userInfo'))?.id) setSearchHistory(item.historyList)
      })
    }
  }, [deleteStatus])
  const [value, setValue] = useState()
  // 处理输入框禁止输入空格
  const handleSpaces = (e) => {
    setValue(e.target.value.replace(/\s+/gu, ''))
  }
  useEffect(() => {
    setValue(searchWord)
  }, [searchWord])
  // 获取搜索词条
  useEffect(() => {
    searchTermModel.getSearchTermList({
      data: {}
    }).then(({datas}) => {
      if (datas && datas.list) {
        datas.list.forEach(item => item.is_default === 1 && setSearchTermDefault(item.title))
        setSearchTermList(datas.list)
      }
    })
  }, [])
  const deleteHistoryItem = (text) => {
    const historyList = storage.get('next_blog_search_history')
    if (historyList) {
      historyList.forEach(item => {
        if (item.id === JSON.parse(storage.get('next_blog_userInfo'))?.id) {
          item.historyList.splice(item.historyList.indexOf(text), 1)
        }
      })
      storage.set('next_blog_search_history', historyList)
    }
    setDeleteStatus(!deleteStatus)
  }
  const deleteHistory = () => {
    const historyList = storage.get('next_blog_search_history')
    if (historyList) {
      historyList.forEach((item, index) => {
        if (item.id === JSON.parse(storage.get('next_blog_userInfo'))?.id) {
          historyList.splice(index, 1)
        }
      })
      storage.set('next_blog_search_history', historyList)
    }
    setSearchHistory([])
  }
  return (
    <div className={styles.search} >
      <SearchOutlined className={styles.search_icon} />
      <input placeholder="搜索" value={searchWord}  className={styles.search_input} onClick={() => setIsModalVisible(true)} />
      <Tooltip placement="bottom" title="唤起搜索框" color="#1e80ff"> 
        <div className={styles.search_key} onClick={searchBox}>
          <kbd className={styles.key}>
            <span><Image src={Ctrl} /></span>
          </kbd>
          <kbd className={styles.key}>
            <span>Q</span>
          </kbd>
        </div>
      </Tooltip>
      <Modal  footer={null} width={600}  closable={false} visible={isModalVisible} onOk={close} onCancel={close} className="search">
        <Search allowClear onChange={(e) => handleSpaces(e)} value={value} placeholder={searchTermDefault} size="large" onSearch={onSearch} enterButton />
        <Divider orientation="left" style={{marginBottom: 0}} plain><span style={{color: '#8590a6'}}>搜索发现</span></Divider>
        <List
          size="small"
          dataSource={searchTermList}
          split={false}
          renderItem={item => item.is_default === 0 && <List.Item onClick={() => onSearch(item.title)}  className={styles.list_item} key={item.id} style={{cursor: 'pointer', padding: '3px 16px'}}>{item.title}</List.Item>}
        />
        {
          searchHistory.length > 0 &&  
          <>
            <Divider orientation="left" style={{marginBottom: 0}} plain><span style={{color: '#8590a6'}}>搜索历史</span></Divider>
            <div style={{display: 'flex', justifyContent: 'flex-end'}}><Button type="text" style={{color: '#8590a6'}}  onClick={deleteHistory} icon={<DeleteOutlined></DeleteOutlined>}>删除</Button></div>
            <div style={{maxHeight: 150, overflowY: 'auto'}} className="scrollbar">
              <List
                size="small"
                dataSource={searchHistory}
                split={false}
                renderItem={item => <List.Item key={item} onClick={() => onSearch(item)}  actions={[<Button key="list-btn" type="text" style={{color: '#8590a6'}} onClick={() => deleteHistoryItem(item)} icon={<CloseOutlined></CloseOutlined>}></Button>]} className={styles.list_item} style={{cursor: 'pointer', padding: '3px 16px'}}>{item}</List.Item>}
              />
            </div>
          </>
        }
      </Modal>
    </div>
  )
}
export default SearchBar